package com.bblocks.common.anti_reptile.rule;

import com.bblocks.common.anti_reptile.config.bean.RuleComm;
import com.bblocks.common.anti_reptile.config.bean.UserRule;
import com.bblocks.common.anti_reptile.service.TokenService;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author Jin
 * @since 2024/3/23 14:40
 */
public abstract class AbstractRule implements AntiReptileRule {


    @Override
    public RuleComm match(HttpServletRequest request, HttpServletResponse response) {
        return doMatch(request,response);
    }

    /**
     * 执行
     * @param request
     * @param response
     * @return true则符合规则
     */
    protected abstract RuleComm doMatch(HttpServletRequest request, HttpServletResponse response);


    protected String userId(HttpServletRequest request, RuleComm userRule, TokenService tokenService){
        if(userRule.getTokenKey() == null || userRule.getTokenKey().isEmpty())
            return null;
        String token = request.getHeader(userRule.getTokenKey());
        if(token == null || token.isEmpty()){
            return null;
        }

        String userId =  tokenService.token2UserId(request,token);
        if(userId == null || userId.isEmpty()){//非登录状态
            return null;
        }else
            return userId;
    }
}
